"""
自定义状态栏组件
"""

from PyQt5.QtWidgets import (
    QWidget, QHBoxLayout, QVBoxLayout, QLabel, QProgressBar,
    QPushButton, QFrame
)
from PyQt5.QtCore import Qt, QTimer, pyqtSignal
from PyQt5.QtGui import QFont, QPixmap, QIcon
import datetime

class StatusBarWidget(QWidget):
    """自定义状态栏组件"""
    
    # 信号定义
    message_clicked = pyqtSignal(str)
    
    def __init__(self, parent=None):
        super().__init__(parent)
        
        self.setup_ui()
        self.setup_style()
        
        # 消息计时器
        self.message_timer = QTimer()
        self.message_timer.timeout.connect(self.clear_message)
        
        # 进度计时器
        self.progress_timer = QTimer()
        self.progress_timer.timeout.connect(self.update_progress)
        self.progress_value = 0
    
    def setup_ui(self):
        """设置用户界面"""
        layout = QHBoxLayout(self)
        layout.setContentsMargins(8, 4, 8, 4)
        layout.setSpacing(12)
        
        # 状态消息
        self.status_label = QLabel("🟢 就绪")
        self.status_label.setFont(QFont("Microsoft YaHei", 9))
        layout.addWidget(self.status_label)
        
        # 分隔符
        separator1 = QFrame()
        separator1.setFrameShape(QFrame.VLine)
        separator1.setStyleSheet("color: #e0e0e0; max-width: 1px;")
        layout.addWidget(separator1)
        
        # 进度条（默认隐藏）
        self.progress_bar = QProgressBar()
        self.progress_bar.setVisible(False)
        self.progress_bar.setFixedWidth(200)
        layout.addWidget(self.progress_bar)
        
        layout.addStretch()
        
        # 数据库状态
        self.db_status_label = QLabel("🗄️ 数据库：已连接")
        self.db_status_label.setFont(QFont("Microsoft YaHei", 9))
        layout.addWidget(self.db_status_label)
        
        # 分隔符
        separator2 = QFrame()
        separator2.setFrameShape(QFrame.VLine)
        separator2.setStyleSheet("color: #e0e0e0; max-width: 1px;")
        layout.addWidget(separator2)
        
        # 用户信息
        self.user_label = QLabel("👤 管理员")
        self.user_label.setFont(QFont("Microsoft YaHei", 9))
        layout.addWidget(self.user_label)
        
        # 分隔符
        separator3 = QFrame()
        separator3.setFrameShape(QFrame.VLine)
        separator3.setStyleSheet("color: #e0e0e0; max-width: 1px;")
        layout.addWidget(separator3)
        
        # 时间
        self.time_label = QLabel()
        self.time_label.setFont(QFont("Microsoft YaHei", 9))
        layout.addWidget(self.time_label)
        
        # 更新时间
        self.update_time()
        
        # 时间计时器
        self.time_timer = QTimer()
        self.time_timer.timeout.connect(self.update_time)
        self.time_timer.start(1000)  # 每秒更新
    
    def setup_style(self):
        """设置样式"""
        self.setStyleSheet("""
            QLabel {
                color: #666666;
                padding: 2px 4px;
            }
            QProgressBar {
                border: 1px solid #e0e0e0;
                border-radius: 3px;
                text-align: center;
                background-color: #f5f5f5;
            }
            QProgressBar::chunk {
                background-color: #1976d2;
                border-radius: 2px;
            }
        """)
    
    def update_time(self):
        """更新时间显示"""
        current_time = datetime.datetime.now()
        time_str = current_time.strftime("%Y-%m-%d %H:%M:%S")
        self.time_label.setText(f"🕒 {time_str}")
    
    def set_status(self, message, status_type="info", timeout=0):
        """设置状态消息
        
        Args:
            message: 消息内容
            status_type: 状态类型 (info, success, warning, error)
            timeout: 超时时间(毫秒)，0表示不自动清除
        """
        # 设置图标和颜色
        icon_map = {
            "info": "🔵",
            "success": "🟢", 
            "warning": "🟡",
            "error": "🔴"
        }
        
        color_map = {
            "info": "#2196f3",
            "success": "#4caf50",
            "warning": "#ff9800", 
            "error": "#f44336"
        }
        
        icon = icon_map.get(status_type, "🔵")
        color = color_map.get(status_type, "#2196f3")
        
        self.status_label.setText(f"{icon} {message}")
        self.status_label.setStyleSheet(f"color: {color}; padding: 2px 4px;")
        
        # 设置超时清除
        if timeout > 0:
            self.message_timer.start(timeout)
        else:
            self.message_timer.stop()
    
    def clear_message(self):
        """清除消息"""
        self.message_timer.stop()
        self.status_label.setText("🟢 就绪")
        self.status_label.setStyleSheet("color: #666666; padding: 2px 4px;")
    
    def show_progress(self, message="处理中..."):
        """显示进度条"""
        self.progress_bar.setVisible(True)
        self.progress_bar.setRange(0, 0)  # 不确定进度
        self.progress_value = 0
        self.set_status(message, "info")
    
    def show_determinate_progress(self, maximum=100, message="处理中..."):
        """显示确定进度条"""
        self.progress_bar.setVisible(True)
        self.progress_bar.setRange(0, maximum)
        self.progress_bar.setValue(0)
        self.progress_value = 0
        self.set_status(message, "info")
    
    def update_progress(self):
        """更新进度"""
        if self.progress_bar.isVisible() and self.progress_bar.maximum() > 0:
            self.progress_value += 1
            if self.progress_value <= self.progress_bar.maximum():
                self.progress_bar.setValue(self.progress_value)
            else:
                self.hide_progress()
    
    def set_progress_value(self, value):
        """设置进度值"""
        if self.progress_bar.isVisible():
            self.progress_bar.setValue(value)
    
    def hide_progress(self):
        """隐藏进度条"""
        self.progress_bar.setVisible(False)
        self.progress_timer.stop()
        self.clear_message()
    
    def set_db_status(self, connected=True):
        """设置数据库状态"""
        if connected:
            self.db_status_label.setText("🗄️ 数据库：已连接")
            self.db_status_label.setStyleSheet("color: #4caf50; padding: 2px 4px;")
        else:
            self.db_status_label.setText("🗄️ 数据库：未连接")
            self.db_status_label.setStyleSheet("color: #f44336; padding: 2px 4px;")
    
    def set_user(self, username):
        """设置用户信息"""
        self.user_label.setText(f"👤 {username}")
    
    def show_error(self, message, timeout=5000):
        """显示错误消息"""
        self.set_status(message, "error", timeout)
    
    def show_warning(self, message, timeout=3000):
        """显示警告消息"""
        self.set_status(message, "warning", timeout)
    
    def show_success(self, message, timeout=3000):
        """显示成功消息"""
        self.set_status(message, "success", timeout)
    
    def show_info(self, message, timeout=0):
        """显示信息消息"""
        self.set_status(message, "info", timeout)